<script setup lang="ts">
defineOptions({
  name: 'HomePage',
})

import { onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useBlogStore } from '@/stores/useBlogStore'
import TextType from '@/components/vuebits/TextType.vue'
import { Motion } from 'motion-v'
import type { Timestamp } from '@/types/blog.types'

const blogStore = useBlogStore()
const { featuredArticles, recentArticles, categories, tags, loading } = storeToRefs(blogStore)

// 初始化数据
onMounted(async () => {
  try {
    console.log('开始初始化数据...')
    await blogStore.initializeData()
    console.log('数据初始化完成:', {
      articles: blogStore.articles?.length || 0,
      featuredArticles: blogStore.featuredArticles?.length || 0,
      recentArticles: blogStore.recentArticles?.length || 0,
      categories: blogStore.categories?.length || 0,
      tags: blogStore.tags?.length || 0,
    })
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 可以在这里添加用户友好的错误提示
    // 比如显示 toast 通知或错误页面
  }
})

// 简单的日期格式化
const formatDate = (date: Timestamp) => {
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<template>
  <div class="min-h-screen">
    <!-- Hero Section -->
    <section class="hero-section hero min-h-screen relative overflow-hidden">
      <div class="hero-overlay bg-opacity-20"></div>
      <div class="hero-content text-center text-neutral-content relative z-10">
        <div class="max-w-4xl">
          <Motion
            :initial="{ opacity: 0, y: 50 }"
            :animate="{ opacity: 1, y: 0 }"
            :duration="0.8"
            tag="h1"
            class="text-5xl md:text-7xl font-bold mb-6 hero-title-text min-h-[120px] md:min-h-[160px] flex items-center justify-center"
          >
            <TextType
              :text="['欢迎来到我的博客', '分享技术见解', '记录成长历程', '探索前端开发']"
              :typingSpeed="100"
              :pauseDuration="2000"
              :deletingSpeed="50"
              :showCursor="true"
              cursorCharacter="|"
              :loop="true"
              :initialDelay="500"
              :startOnVisible="true"
              className="text-center"
              :textColors="['hsl(var(--nc))', 'hsl(var(--p))', 'hsl(var(--s))', 'hsl(var(--a))']"
            />
          </Motion>

          <Motion
            :initial="{ opacity: 0, y: 30 }"
            :animate="{ opacity: 1, y: 0 }"
            :duration="0.8"
            :delay="0.2"
            tag="div"
            class="text-xl md:text-2xl mb-8 text-base-content/80 max-w-2xl mx-auto min-h-[80px] flex items-center justify-center"
          >
            <TextType
              :text="[
                '💡 创新思维，技术驱动',
                '🚀 持续学习，不断进步',
                '🎯 专注品质，追求卓越',
                '🌟 分享知识，共同成长',
              ]"
              :typingSpeed="80"
              :pauseDuration="3000"
              :deletingSpeed="40"
              :showCursor="true"
              cursorCharacter="_"
              :loop="true"
              :initialDelay="3000"
              :startOnVisible="true"
              className="text-center"
              :textColors="['hsl(var(--nc))', 'hsl(var(--p))', 'hsl(var(--s))', 'hsl(var(--a))']"
            />
          </Motion>

          <Motion
            :initial="{ opacity: 0, scale: 0.8 }"
            :animate="{ opacity: 1, scale: 1 }"
            :duration="0.6"
            :delay="0.4"
            class="flex flex-col sm:flex-row gap-4 justify-center items-center"
          >
            <button
              @click="$router.push('/blog')"
              class="btn btn-primary btn-lg gap-2 shadow-lg hover:shadow-xl transition-all duration-300"
            >
              <PhBookOpen class="w-5 h-5" />
              开始阅读
            </button>
            <button
              @click="$router.push('/about')"
              class="btn btn-outline btn-lg gap-2 hover:scale-105 transition-all duration-300"
            >
              <PhInfo class="w-5 h-5" />
              了解更多
            </button>
          </Motion>
        </div>
      </div>

      <!-- 装饰性背景元素 -->
      <Motion
        :initial="{ opacity: 0, scale: 0 }"
        :animate="{ opacity: 0.6, scale: 1 }"
        :duration="1.2"
        :delay="0.6"
        class="absolute top-20 left-20 w-72 h-72 bg-primary/20 rounded-full blur-3xl"
      />
      <Motion
        :initial="{ opacity: 0, scale: 0 }"
        :animate="{ opacity: 0.4, scale: 1 }"
        :duration="1.2"
        :delay="0.8"
        class="absolute bottom-20 right-20 w-96 h-96 bg-secondary/20 rounded-full blur-3xl"
      />
    </section>

    <!-- Loading State -->
    <div v-if="loading" class="flex justify-center items-center py-20">
      <div class="loading loading-spinner loading-lg text-primary"></div>
      <span class="ml-4 text-lg loading-text">加载中...</span>
    </div>

    <!-- Featured Articles -->
    <section v-if="featuredArticles.length > 0" class="py-8 sm:py-12 md:py-16 bg-base-100">
      <div class="container mx-auto px-4">
        <Motion
          :initial="{ opacity: 0, y: 30 }"
          :animate="{ opacity: 1, y: 0 }"
          :duration="0.6"
          visible-once
          tag="h2"
          class="text-3xl sm:text-4xl md:text-5xl font-bold text-center mb-8 sm:mb-10 md:mb-12 min-h-[60px] sm:min-h-[80px] flex items-center justify-center"
          style="color: hsl(var(--bc))"
        >
          <TextType
            :text="['✨ 特色文章', '🌟 精选内容', '📖 推荐阅读']"
            :typingSpeed="120"
            :pauseDuration="4000"
            :deletingSpeed="60"
            :showCursor="true"
            cursorCharacter="✦"
            :loop="true"
            :startOnVisible="true"
            className="text-center"
            :textColors="['hsl(var(--bc))', 'hsl(var(--p))', 'hsl(var(--s))']"
          />
        </Motion>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 md:gap-8">
          <Motion
            v-for="(article, index) in featuredArticles"
            :key="article.id"
            :initial="{ opacity: 0, y: 50, scale: 0.9 }"
            :animate="{ opacity: 1, y: 0, scale: 1 }"
            :duration="0.5"
            :delay="index * 0.15"
            visible-once
          >
            <div
              @click="$router.push(`/blog/${article.slug}`)"
              class="card card-themed bg-base-100 shadow-xl hover:shadow-2xl cursor-pointer transition-all duration-300 hover:-translate-y-2 group h-full flex flex-col"
            >
              <figure class="relative overflow-hidden">
                <img
                  :src="article.coverImage || `https://picsum.photos/400/240?random=${article.id}`"
                  :alt="article.title"
                  class="w-full h-40 sm:h-48 object-cover transition-transform duration-300 group-hover:scale-110"
                />
                <div class="absolute top-3 sm:top-4 left-3 sm:left-4">
                  <div
                    class="badge badge-primary badge-sm sm:badge-lg font-semibold text-xs sm:text-sm"
                  >
                    {{ article.category.name }}
                  </div>
                </div>
                <div class="absolute top-3 sm:top-4 right-3 sm:right-4">
                  <div
                    class="badge badge-ghost bg-base-100/80 text-base-content badge-sm sm:badge-md text-xs sm:text-sm"
                  >
                    {{ formatDate(article.publishDate || '') }}
                  </div>
                </div>
              </figure>

              <div class="card-body p-4 sm:p-6 flex-1 flex flex-col">
                <h3
                  class="card-title text-lg sm:text-xl group-hover:text-primary transition-colors"
                >
                  {{ article.title }}
                </h3>
                <p
                  class="text-sm sm:text-base text-base-content/70 leading-relaxed flex-1 line-clamp-3"
                >
                  {{ article.excerpt }}
                </p>

                <div class="card-actions justify-between items-center mt-3 sm:mt-4">
                  <div class="flex flex-wrap gap-1 sm:gap-2">
                    <div
                      v-for="tag in article.tags.slice(0, 3)"
                      :key="tag.id"
                      class="badge badge-outline badge-xs sm:badge-sm hover:badge-primary transition-colors cursor-pointer"
                    >
                      {{ tag.name }}
                    </div>
                  </div>
                  <div
                    class="flex items-center gap-1 sm:gap-2 text-xs sm:text-sm text-base-content/60"
                  >
                    <PhClock class="w-3 h-3 sm:w-4 sm:h-4" />
                    {{ article.readTime }} 分钟
                  </div>
                </div>
              </div>
            </div>
          </Motion>
        </div>
      </div>
    </section>

    <!-- Recent Articles -->
    <section class="py-8 sm:py-12 md:py-16 bg-base-200">
      <!-- Debug Info -->
      <div class="container mx-auto px-4 mb-4 text-sm text-gray-500">
        调试信息: recentArticles.length = {{ recentArticles?.length || 0 }}, articles.length =
        {{ blogStore.articles?.length || 0 }}
      </div>
      <div class="container mx-auto px-4">
        <Motion
          :initial="{ opacity: 0, x: -50 }"
          :animate="{ opacity: 1, x: 0 }"
          :duration="0.6"
          visible-once
          tag="h2"
          class="text-3xl sm:text-4xl md:text-5xl font-bold text-center mb-8 sm:mb-10 md:mb-12 min-h-[60px] sm:min-h-[80px] flex items-center justify-center"
          style="color: hsl(var(--bc))"
        >
          <TextType
            :text="['📝 最新文章', '🔥 热门内容', '📚 近期更新']"
            :typingSpeed="110"
            :pauseDuration="3500"
            :deletingSpeed="55"
            :showCursor="true"
            cursorCharacter="▎"
            :loop="true"
            :startOnVisible="true"
            className="text-center"
            :textColors="['hsl(var(--bc))', 'hsl(var(--er))', 'hsl(var(--p))']"
          />
        </Motion>

        <div class="max-w-4xl mx-auto space-y-4 sm:space-y-6">
          <div v-if="recentArticles.length === 0" class="text-center py-8 text-gray-500">
            暂无最新文章
          </div>
          <Motion
            v-for="(article, index) in recentArticles"
            :key="article.id"
            :initial="{ opacity: 0, x: -100 }"
            :animate="{ opacity: 1, x: 0 }"
            :duration="0.6"
            :delay="index * 0.1"
            visible-once
          >
            <div
              @click="$router.push(`/blog/${article.slug}`)"
              class="card card-side bg-base-100 shadow-lg hover:shadow-xl cursor-pointer transition-all duration-300 hover:translate-x-2 group"
            >
              <figure class="w-24 sm:w-32 md:w-48 flex-shrink-0">
                <img
                  :src="article.coverImage || `https://picsum.photos/200/120?random=${article.id}`"
                  :alt="article.title"
                  class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                />
              </figure>

              <div class="card-body p-4 sm:p-6">
                <div class="flex flex-wrap items-center gap-2 sm:gap-3 mb-2">
                  <div
                    class="badge badge-xs sm:badge-sm font-medium"
                    :style="{
                      backgroundColor: article.category.color + '20',
                      color: article.category.color,
                      borderColor: article.category.color + '40',
                    }"
                  >
                    {{ article.category.name }}
                  </div>
                  <div class="text-xs sm:text-sm text-base-content/60">
                    {{ formatDate(article.publishDate || '') }}
                  </div>
                  <div class="text-xs sm:text-sm text-base-content/60">
                    {{ article.readTime }} 分钟
                  </div>
                </div>

                <h3
                  class="card-title text-base sm:text-lg group-hover:text-primary transition-colors line-clamp-2"
                >
                  {{ article.title }}
                </h3>
                <p
                  class="text-base-content/70 text-xs sm:text-sm leading-relaxed line-clamp-2 hidden sm:block"
                >
                  {{ article.excerpt }}
                </p>

                <div class="card-actions justify-end mt-2">
                  <div class="flex items-center gap-1 text-xs sm:text-sm text-base-content/60">
                    <svg
                      class="w-3 h-3 sm:w-4 sm:h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                      />
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                      />
                    </svg>
                    {{ article.viewCount }}
                  </div>
                </div>
              </div>
            </div>
          </Motion>
        </div>
      </div>
    </section>

    <!-- Categories & Tags -->
    <section class="py-8 sm:py-12 md:py-16 bg-base-100">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 sm:gap-10 md:gap-12">
          <!-- Categories -->
          <Motion
            :initial="{ opacity: 0, x: -50 }"
            :animate="{ opacity: 1, x: 0 }"
            :duration="0.6"
            visible-once
          >
            <h2
              class="text-2xl sm:text-3xl md:text-4xl font-bold mb-6 sm:mb-8 min-h-[50px] sm:min-h-[60px] flex items-center"
              style="color: hsl(var(--bc))"
            >
              <TextType
                :text="['📂 文章分类', '🗂️ 内容分类', '📋 主题分类']"
                :typingSpeed="100"
                :pauseDuration="4000"
                :deletingSpeed="50"
                :showCursor="true"
                cursorCharacter="📁"
                :loop="true"
                :startOnVisible="true"
                :textColors="['hsl(var(--bc))', 'hsl(var(--p))', 'hsl(var(--s))']"
              />
            </h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
              <Motion
                v-for="(category, index) in categories"
                :key="category.id"
                :initial="{ opacity: 0, scale: 0.8 }"
                :animate="{ opacity: 1, scale: 1 }"
                :duration="0.4"
                :delay="index * 0.1"
                visible-once
              >
                <div
                  @click="$router.push(`/blog/category/${category.slug}`)"
                  class="card bg-base-100 shadow-md hover:shadow-lg cursor-pointer transition-all duration-200 hover:scale-105 group"
                >
                  <div class="card-body p-3 sm:p-4">
                    <div class="flex items-center gap-2 sm:gap-3">
                      <div
                        class="w-3 h-3 sm:w-4 sm:h-4 rounded-full flex-shrink-0"
                        :style="{ backgroundColor: category.color }"
                      ></div>
                      <div class="flex-1 min-w-0">
                        <h3
                          class="text-sm sm:text-base font-semibold text-base-content group-hover:text-primary transition-colors truncate"
                        >
                          {{ category.name }}
                        </h3>
                        <p class="text-xs sm:text-sm text-base-content/60">
                          {{ category.articleCount }} 篇文章
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </Motion>
            </div>
          </Motion>

          <!-- Tags -->
          <Motion
            :initial="{ opacity: 0, x: 50 }"
            :animate="{ opacity: 1, x: 0 }"
            :duration="0.6"
            :delay="0.2"
            visible-once
          >
            <h2
              class="text-2xl sm:text-3xl md:text-4xl font-bold mb-6 sm:mb-8 min-h-[50px] sm:min-h-[60px] flex items-center"
              style="color: hsl(var(--bc))"
            >
              <TextType
                :text="['🏷️ 热门标签', '🔖 标签云', '🎯 关键词']"
                :typingSpeed="95"
                :pauseDuration="3800"
                :deletingSpeed="45"
                :showCursor="true"
                cursorCharacter="🏷️"
                :loop="true"
                :startOnVisible="true"
                :textColors="['hsl(var(--bc))', 'hsl(var(--a))', 'hsl(var(--s))']"
              />
            </h2>
            <div class="flex flex-wrap gap-2 sm:gap-3">
              <Motion
                v-for="(tag, index) in tags"
                :key="tag.id"
                :initial="{ opacity: 0, scale: 0 }"
                :animate="{ opacity: 1, scale: 1 }"
                :duration="0.3"
                :delay="index * 0.05"
                visible-once
              >
                <div
                  @click="$router.push(`/blog/tag/${tag.slug}`)"
                  class="badge badge-sm sm:badge-md lg:badge-lg badge-outline hover:badge-primary cursor-pointer transition-all duration-200 hover:scale-110 hover:-translate-y-1 p-2 sm:p-3 text-xs sm:text-sm"
                >
                  {{ tag.name }} ({{ tag.articleCount }})
                </div>
              </Motion>
            </div>
          </Motion>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
/* 英雄标题文字样式 - 解决TextType组件文字模糊问题 */
.hero-title-text {
  /* 确保文字渲染清晰 */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;

  /* 移除可能导致模糊的CSS属性 */
  -webkit-text-fill-color: unset;
  background-clip: unset;
  -webkit-background-clip: unset;

  /* 确保TextType组件的颜色能正常显示 */
  color: inherit;
}

/* 为TextType组件内的文字提供更好的渲染 */
.hero-title-text :deep(span) {
  /* 确保动态文字颜色正常显示 */
  -webkit-text-fill-color: unset !important;
  background-clip: unset !important;
  -webkit-background-clip: unset !important;

  /* 优化文字渲染 */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;

  /* 确保文字有足够的对比度 */
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
</style>
